package com.sams.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sams.entity.Authority;
import com.sams.entity.AuthorityExample;
import com.sams.entity.RRoleAuthority;
import com.sams.entity.RRoleAuthorityExample;
import com.sams.entity.User;
import com.sams.entity.UserExample;
import com.sams.entity.RRoleAuthorityExample.Criteria;
import com.sams.mapper.AuthorityMapper;
import com.sams.mapper.RRoleAuthorityMapper;
import com.sams.service.AuthorityService;
@Service
public class AuthorityServiceImpl implements AuthorityService{

	@Autowired
	private AuthorityMapper mapper;
	
	@Autowired
	private RRoleAuthorityMapper rmapper;
	
	
	public List<Authority> selectAthorByRoleId(int roleId) {
		 
		return mapper.selectAthorByRoleId(roleId);
	}
 
	
	public int add(Authority authority) {
		//添加两张表 
		// 1  权限表 
		int count = mapper.insert(authority);
		if(count>0) {
			if(authority.getRoleids()!=null) {
				System.out.println(authority.getRoleids().length+"============");
				for(int i=0;i<authority.getRoleids().length;i++) {
					RRoleAuthority rRoleAuthority = new RRoleAuthority();
					rRoleAuthority.setAuthorityid(authority.getId());
					rRoleAuthority.setRoleid(new Integer(authority.getRoleids()[i]));
					rmapper.insert(rRoleAuthority);
				}
			}
		}
		//2  中间表 
		return count;
	}

	public PageInfo<Authority> listByPage(Integer currentPage) {
		// 1 定义当前页  和 一页显示的行数 
		  PageHelper.startPage(currentPage, 20);  
		 
		
		  AuthorityExample example = new AuthorityExample();
		 com.sams.entity.AuthorityExample.Criteria createCriteria = example.createCriteria();
		 
		 // 2  调用查询语句
		List<Authority> list =   mapper.selectAthorList(example);
		
		PageInfo<Authority> pageInfo = new PageInfo<Authority>(list);
		return pageInfo;
		
		
		
	//	return null;
	}
	/**
	 * 删除两张表
	 */
	public int delete(Integer auid,Integer roleid) {
		boolean flag =false;
		
		//先根据权限id 查询 如果只有一条记录 ，就全部删除 ，如果大于1条记录，就不删除权限表 记录 
		RRoleAuthorityExample example = new RRoleAuthorityExample();
		Criteria criteria2 = example.createCriteria();
		criteria2.andAuthorityidEqualTo(auid);
		List<RRoleAuthority> list = rmapper.selectByExample(example);
		if(list.size()>1) {
			//不删除
			
		}else {
			//删除 当前权限 
		   flag=true;
		}
		
		
	     //先删除  中间表 
		RRoleAuthorityExample example1 = new RRoleAuthorityExample();
		Criteria criteria = example1.createCriteria();
		criteria.andAuthorityidEqualTo(auid);//权限id
		criteria.andRoleidEqualTo(roleid);// 角色id 
		int count = rmapper.deleteByExample(example1);

		if(flag) {
			mapper.deleteByPrimaryKey(auid);
		}
		//再删除 权限表  
		return count;
		
	}

 
}
